import { Injectable } from '@nestjs/common';
import { CreateNodeDto } from './dto/create-node.dto';
import { UpdateNodeDto } from './dto/update-node.dto';
import { ResponseUtil } from '../common/utils/response.util';
import { forwardRef, Inject } from '@nestjs/common';
import { WebsocketGateway } from '../websocket/websocket.gateway';
@Injectable()
export class NodeService {

  constructor(private websocketGateway:WebsocketGateway){}
   
  // 已部署节点信息
    public deployedNodes = Array.from({length:300},(_,i)=>{
      // 使用随机数来分配节点类型，确保有type为3的节点
      const nodeTypes = [0, 1, 2]; // 0:虚拟节点 1:真实节点 2:宿主机
      const randomTypeIndex = Math.floor(Math.random() * nodeTypes.length);
      const nodeType = nodeTypes[randomTypeIndex];
      const orbitTypes = [1,2,3] //1低轨,2中轨,3地球同步轨
      const randomOrbitTypeIndex = Math.floor(Math.random() * orbitTypes.length);
      const orbitType = orbitTypes[randomOrbitTypeIndex];
      return  {
        connectionStatus: i%2==0?0:1, //0:未连接 1:已连接
        createdBy: "",
        nodeName: `node${i+1}`,
        createdTime: 1743563766000,
        id: i+1,
        ipAddress: `192.168.${i+1}.${i+1}`,
        nodeId: i+1,
        orbitType: orbitType, // 
        type: nodeType, // 使用随机生成的节点类型
        updatedBy: "",
        faultInjection:Math.floor(Math.random()*2), //0:未注入,1:已注入
        updatedTime: new Date().getTime(),
        port:"192.168.1."+i,//故障注入端口,
        injectionType:Math.floor(Math.random()*5),//生成0-4随机数
        parameter:"",//故障注入参数
        startupScript:`startupScriptstartupScriptstartupScriptstartupScript${i + 1}`,//启动脚本,
        deployCount:Math.floor(Math.random()*100),//部署物数量
        cpu: Math.floor(Math.random() * 100),
        disk: Math.floor(Math.random() * 100),
        memory: Math.floor(Math.random() * 100),
      }
    })  
    // 部署文件信息
    public deploymentFiles = Array.from({length:20},(_,i)=>{
      return {
        deploymentName:"部署文件"+i,
        deploymentId:i,
        versionNumber:i,
        updateTime:new Date().getTime()+i,
        runningStatus:i%2==0?0:1, //0:停止 1:已运行,
        ipAddress:"192.168.1."+i,
      }
    })

  //分页查询
  async getPage(body) {
   const {pageSize,currentPage,nodeId,ipAddress,connectionStatus,type,injectionType,faultInjection} = body
   let records = this.deployedNodes.filter(item=>{
    const nodeIdMatch = nodeId === undefined || nodeId === null || nodeId === "" || item.nodeId == nodeId
    const ipAddressMatch = ipAddress === undefined || ipAddress === null || ipAddress === "" || item.ipAddress == ipAddress
    const connectionStatusMatch = connectionStatus === undefined || connectionStatus === null || connectionStatus === "" || item.connectionStatus == connectionStatus
    const typeMatch = type === undefined || type === null || type === "" || item.type == type
    const injectionTypeMatch = injectionType === undefined || injectionType === null || injectionType === "" || item.injectionType == injectionType
    const faultInjectionMatch = faultInjection === undefined || faultInjection === null || faultInjection === "" || item.faultInjection == faultInjection
    return nodeIdMatch && ipAddressMatch && connectionStatusMatch && typeMatch && injectionTypeMatch && faultInjectionMatch
   })
   const filteredTotal = records.length
   const start = (currentPage - 1) * pageSize
   const end = start + pageSize
   records = records.slice(start,end)
   const data = {
    records,
    total: filteredTotal, // 使用过滤后的记录数作为总数
   }
   return ResponseUtil.success(data, 'Get deployed nodes');
  }

  //  获取已部署节点
  async getDeployedNodes(body) {
    const { pageSize, currentPage, deploymentId } = body
    
    // 获取所有节点（不基于deploymentId过滤，因为节点对象中没有该字段）
    let filteredNodes = [...this.deployedNodes];
    
    const total = filteredNodes.length;
    const start = (currentPage - 1) * pageSize;
    const end = start + pageSize;
    const records = filteredNodes.slice(start, end);
    
    const data = {
      records,
      total,
    }
    return ResponseUtil.success(data, 'Get deployed nodes');
  }

  // 获取可部署节点
  async getUndeployedNodes(body) {
    const { pageSize, currentPage,deploymentId } = body
    const start = (currentPage - 1) * pageSize
    const end = start + pageSize
    const records = this.deployedNodes.slice(start,end)
    const data = {
      records,
      total: this.deployedNodes.length,
    }
    return ResponseUtil.success(data, 'Get undeployed nodes');
  }

  // 节点条件查询
  async queryList(body:any) {
    const {nodeId,ipAddress,connectionStatus,type} = body
    const records = this.deployedNodes.filter(item => {
      // 只有当参数有值且不为空字符串时才进行过滤
      const matchNodeId = nodeId === undefined || nodeId === null || nodeId === "" || item.nodeId == nodeId
      const matchIpAddress = ipAddress === undefined || ipAddress === null || ipAddress === "" || item.ipAddress == ipAddress
      const matchConnectionStatus = connectionStatus === undefined || connectionStatus === null || connectionStatus === "" || item.connectionStatus == connectionStatus
      const matchType = type === undefined || type === null || type === "" || item.type == type
      // 所有传入的条件都必须满足（与逻辑）
      return matchNodeId && matchIpAddress && matchConnectionStatus && matchType;
    });
    return ResponseUtil.success(records, 'Query node list');
  }

  //根据节点ID获取部署文件信息
  async getNodeDepFile(body) {
    const {currentPage,pageSize} = body
    const start = (currentPage - 1) * pageSize
    const end = start + pageSize
    const records = this.deploymentFiles.slice(start,end)
    const data  = {
      records,
      total:this.deploymentFiles.length
    }
    return ResponseUtil.success(data, 'Get node deployment file');
  }

  //批量删除节点
  async batchDeleteNode(body) {
   console.log(body,"body");
    this.deployedNodes = this.deployedNodes.filter(item=>!body.includes(item.id))
    return ResponseUtil.success(null, 'Batch delete node');
  }


  // 获取节点cpu和内存数据
  async getNodeCpuAndMem(body) {
    console.log(body,"body");
    const ips = body.ips
    const data = {}
    await new Promise((resolve)=>{
      setTimeout(()=>{
        this.websocketGateway.pushCpuAndMem(ips)
        resolve(true)
      },1000)
    })
    return ResponseUtil.success(data, 'Get node cpu and mem');
  }

  // 故障注入
  async faultInjection(body) {
    return ResponseUtil.success(null, 'Fault injection');
  }

  // 停止故障注入
  async stopFaultInjection(body) {
    return ResponseUtil.success(null, 'Stop fault injection');
  }


  //获取排除宿主机的所有节点
  async getNodesExcludeHost(body) {
    const {currentPage,pageSize,nodeId,ipAddress,connectionStatus,type,nodeName} = body
    let records = this.deployedNodes.filter(item=>{
      const nodeIdMatch = nodeId === undefined || nodeId === null || nodeId === "" || item.nodeId == nodeId
      const ipAddressMatch = ipAddress === undefined || ipAddress === null || ipAddress === "" || item.ipAddress == ipAddress
      const connectionStatusMatch = connectionStatus === undefined || connectionStatus === null || connectionStatus === "" || item.connectionStatus == connectionStatus
      const typeMatch = type === undefined || type === null || type === "" || item.type == type
      const nodeNameMatch = nodeName === undefined || nodeName === null || nodeName === "" || item.nodeName == nodeName
      return nodeIdMatch && ipAddressMatch && connectionStatusMatch && typeMatch && nodeNameMatch
    })
    const filteredTotal = records.length
    const start = (currentPage - 1) * pageSize
    const end = start + pageSize
    records = records.slice(start,end)
    const data = {
      records,
      total: filteredTotal, // 使用过滤后的记录数作为总数
    }
    return ResponseUtil.success(data, 'Get nodes exclude host');
  }

  // 保存和修改节点
  async saveOrUpdate(body) {
    const {nodeId} = body
    const index = this.deployedNodes.findIndex(item=>item.nodeId==nodeId)
    if(index!=-1){
      this.deployedNodes[index] = body
    }else{
      this.deployedNodes.push(body)
    }
    return ResponseUtil.success(null, 'Save or update node');
  }

  // 节点查询所有节点,排除宿主机
  async queryAllNodes(body) {
    const data = [
      {
        id: 11919,
        nodeId: 12595,
        ipAddress: '172.16.7.120',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748418711000,
        updateTime: 1748418711000,
        createId: '',
        updateId: '',
      },
      {
        id: 11918,
        nodeId: 12593,
        ipAddress: '172.16.7.119',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748418457000,
        updateTime: 1748418457000,
        createId: '',
        updateId: '',
      },
      {
        id: 11917,
        nodeId: 12591,
        ipAddress: '172.16.7.118',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 3,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417872000,
        updateTime: 1748418132000,
        createId: '',
        updateId: '',
      },
      {
        id: 11914,
        nodeId: 12583,
        ipAddress: '172.16.7.109',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417412000,
        updateTime: 1748417412000,
        createId: '',
        updateId: '',
      },
      {
        id: 11915,
        nodeId: 12586,
        ipAddress: '172.16.7.111',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417412000,
        updateTime: 1748417412000,
        createId: '',
        updateId: '',
      },
      {
        id: 11916,
        nodeId: 12587,
        ipAddress: '172.16.7.106',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417412000,
        updateTime: 1748417412000,
        createId: '',
        updateId: '',
      },
      {
        id: 11913,
        nodeId: 12581,
        ipAddress: '172.16.7.112',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417411000,
        updateTime: 1748417411000,
        createId: '',
        updateId: '',
      },
      {
        id: 11911,
        nodeId: 12577,
        ipAddress: '172.16.7.107',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417410000,
        updateTime: 1748417410000,
        createId: '',
        updateId: '',
      },
      {
        id: 11912,
        nodeId: 12579,
        ipAddress: '172.16.7.115',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417410000,
        updateTime: 1748417410000,
        createId: '',
        updateId: '',
      },
      {
        id: 11910,
        nodeId: 12575,
        ipAddress: '172.16.7.110',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417409000,
        updateTime: 1748417409000,
        createId: '',
        updateId: '',
      },
      {
        id: 11909,
        nodeId: 12573,
        ipAddress: '172.16.7.113',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417408000,
        updateTime: 1748417408000,
        createId: '',
        updateId: '',
      },
      {
        id: 11908,
        nodeId: 12571,
        ipAddress: '172.16.7.114',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417406000,
        updateTime: 1748417406000,
        createId: '',
        updateId: '',
      },
      {
        id: 11905,
        nodeId: 12565,
        ipAddress: '172.16.7.108',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417404000,
        updateTime: 1748417404000,
        createId: '',
        updateId: '',
      },
      {
        id: 11906,
        nodeId: 12567,
        ipAddress: '172.16.7.116',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417404000,
        updateTime: 1748417404000,
        createId: '',
        updateId: '',
      },
      {
        id: 11907,
        nodeId: 12569,
        ipAddress: '172.16.7.102',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 0,
        runningStatus: null,
        createTime: 1748417404000,
        updateTime: 1748417404000,
        createId: '',
        updateId: '',
      },
      {
        id: 11904,
        nodeId: 12563,
        ipAddress: '172.16.7.101',
        ipv6: null,
        nodeName: null,
        type: 1,
        connectionStatus: 1,
        virtualServerIp: null,
        faultInjection: 0,
        port: null,
        injectionType: null,
        configStatus: null,
        containerId: null,
        orbitType: 1,
        deployCount: 1,
        runningStatus: null,
        createTime: 1748417403000,
        updateTime: 1748417403000,
        createId: '',
        updateId: '',
      },
    ];
   return ResponseUtil.success(data, 'Query all nodes');
}

  //查询在线节点,按部署物数量从大到小排序
  async queryOnline(body) {
    const data = this.deployedNodes.filter(item=>item.connectionStatus==1)
    this.websocketGateway.pushCpuAndMem(data.map(item=>item.ipAddress).slice(0,3))
    return ResponseUtil.success(data, 'Query online nodes');
  }


}